<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>超时与取消请求</title>
</head>
<body>
    <button>发送请求</button>
    <button>取消请求</button>
    <script>
        //获取按钮
        let btns = document.querySelectorAll('button');
        let xhr;
        //第一个按钮
        btns[0].onclick = function(){
            xhr = new XMLHttpRequest(); 
            xhr.open('get', 'http://localhost/delay-server'); //delay 延时
            xhr.send();
            //超时设置
            // xhr.timeout = 2000;//单位是毫秒 
            //事件  超时时会触发的时间
            // xhr.ontimeout = function(){
            //     console.log('请求超时, 请稍后再试~~~');
            // }

            xhr.onreadystatechange = function(){
                //判断
                if(xhr.readyState === 4){
                    //输出响应体
                    console.log(xhr.response);
                }
            }
        }
    
        //取消请求
        btns[1].onclick = function(){
            xhr.abort();
        }
    </script>
</body>
</html>